package aquarium.reseau;

import java.util.HashMap;
import java.util.Vector;

import aquarium.gui.Aquarium;

public class UpdateCollection extends Thread{

	private HashMap<Integer, Vector<String>> _list_packet_aquarium_items;
	private HashMap<Integer, Long> _list_last_time_client = new HashMap<Integer, Long>();
	private Vector<Connection> _list_connection;

	private Vector<String> _value_null;

	private double TIMEOUT = 2500;
	private long _time;

	public void start(HashMap<Integer, Vector<String>> list_packet_aquarium_items, Vector<Connection> list_connection, Aquarium aquarium){
		this._list_packet_aquarium_items = list_packet_aquarium_items;
		this._list_connection = list_connection;
		this._value_null = new Vector<String>();
		this._value_null.add(new String("end"));

		this.start();
	}

	public void run(){

		while(true){
			recup_all_collection();
			timeout_client();
			
			try {
				ClientTCP.sleep((long) 1);
			} catch (Exception e) {
				System.out.println("Exception while trying to sleep. Too mich noise !!! for details see this -> " + e);
			}
		}
	}

	private void recup_all_collection(){

		if(_list_connection.size() != 0){ //Il y a au moins un client
			synchronized(_list_connection){
				Connection connect_tmp;
				Connection other_connect;
				for(int i = 0; i<_list_connection.size(); i++){ // On parcours toutes les connections
					connect_tmp = _list_connection.get(i);
					if(connect_tmp.has_changed()){ // On trouve une connection ou la collection a changer
						_list_packet_aquarium_items.put(connect_tmp.get_id(), new Vector<String>(connect_tmp.get_collection())); // On recupere
						connect_tmp.changed(); // On dit que l'on a recupéré la collection
						_list_last_time_client.put(i, System.currentTimeMillis());
						for(int j = 0; j < _list_connection.size(); j++){ // On envoit aux autres clients la collection
							other_connect = _list_connection.get(j);
							if(j != i)
								other_connect.send_collection(_list_packet_aquarium_items.get(i), i);

						}
					}	
				}
			}
		}
	}

	private void timeout_client(){
		Connection other_connect;
		_time = System.currentTimeMillis();
		synchronized(_list_connection){
			for(int i = 0; i < _list_last_time_client.size(); i++){ // On envoit aux autres clients la collection
				other_connect = _list_connection.get(i);
				other_connect.send_collection(_value_null, i);
				if(_time - _list_last_time_client.get(i) > TIMEOUT){
					for(int j = 0; j < _list_last_time_client.size(); j++){
						other_connect = _list_connection.get(j);
						other_connect.send_collection(new Vector<String>(), i);
					}
				}
			}
		}
	}
}
